package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        //2 生成验证码
        String code = RandomUtil.randomNumbers(6);

        //3 保存验证码到session
        //session.setAttribute("code", code);

        //4 发送验证码,保存到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);


        log.debug("发生短信验证码成功,{}",code);
        //5 返回 ok
        return Result.ok();
    }
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1、校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        //2、校验验证码，从redis中取
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String loginFormCodeode = loginForm.getCode();
        if(!loginFormCodeode.equals(cacheCode) || cacheCode == null){
            //3、不一致报错
            return Result.fail("验证码输入不正确！");
        }
        User user = query().eq("phone", phone).one();
        //5、判断用户是否存在
        if(user == null){
            //6、不存在创建新用户并保存在数据库中
            user = createUserWithPhone(phone);
        }

        //7、保存用户信息到redis中
        //7.1 随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);

        //7.2 将User作为hashMap存储
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        //Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userDTO.getId().toString());
        map.put("nickName", userDTO.getNickName());
        map.put("icon", userDTO.getIcon());

        //7.3 存储
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,map);

        //7.4 设置token的有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public void removeUser(String token) {
        String redisKey = LOGIN_USER_KEY + token;
        String name = (String) stringRedisTemplate.opsForHash().get(redisKey, "nickName");
        log.debug("{},用户退出登录",name);
        stringRedisTemplate.delete(redisKey);
        UserHolder.removeUser();
    }

    @Override
    public Result sign() {
        // 获取当前用户和当前时间
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        // 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId + ":" + keySuffix;
        // 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);

        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 获取当前用户和当前时间
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        // 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId + ":" + keySuffix;
        // 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 获取本月本月所有的签到记录，返回是一个十进制数.
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.
                        create().
                        get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        // 没有任何签到结果
        if(result == null || result.isEmpty()){
            return Result.ok(0);
        }
        // 取出一个月的记录 00100100
        Long num = result.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        // 循环遍历 让这个数字和1作与运算，得到最后一个bit位，为0没签到，为1签到了，计数器加1，数字右移1位
        while (num != 0){
            if ((num & 1) == 1) {
                count++;
            }
            num = num >>> 1;
        }

        return Result.ok(count);
    }


    /*@Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1、校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        //2、校验验证码
        Object cacheCode = session.getAttribute("code");
        String loginFormCodeode = loginForm.getCode();
        if(!loginFormCodeode.equals(cacheCode.toString()) || cacheCode == null){
            //3、不一致报错
            return Result.fail("验证码输入不正确！");
        }
        //4、一致，根据手机号去数据库查询用户 select * from tb_user where phone = ?
        // extends ServiceImpl<UserMapper, User>,mybatis_plus,去查User中的数据
        User user = query().eq("phone", phone).one();
        //5、判断用户是否存在
        if(user == null){
            //6、不存在创建新用户并保存在数据库中
            user = createUserWithPhone(phone);
        }
        //7、保存用户信息到session中
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);

        session.setAttribute("userDTO", userDTO);
        return Result.ok();
    }*/

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
